import React, { Component } from 'react'
import { connect } from 'react-redux'
import moment from 'moment'
import _ from 'underscore'
import DatePicker from 'react-datepicker';
import { Modal } from 'antd';

import table from '../../charts/table'
import { merge, trim, ajax } from '../../helper/helper'
import { ContentHeader } from '../../wrapper'
import { actions } from '../action/action'
// import Modal from '../../common/modal'
import { DetailHeader, DetailEvents, DetailPropertyGroup, DealTimeline } from '../../common/userdetail'
import { eventDateRangeList, eventListType, moreEventMessageTypeList, iconList, lifeCycleList, eventTypeMap } from '../static/index'
import ReactDropDown, { ReactDropDownFull } from '../../common/dropdown'


let time;
class UserDetail extends Component {
    componentDidMount() {
        let self = this;
        time = setInterval(() => {
            self.props.getVisit(self.props.searchTime);
        }, 2000);
    }
    componentWillUnmount() {
        clearInterval(time);
    }

    render() {
        const { location } = this.props;
        const status = location.query.status;
        return <div className="userDetail">
            <_InitialEventListState location={location} />
            <_GetEventListData />
            <_ContentHeader title="客户明细">
                <ol className="breadcrumb">
                    <li><a href="#/crmReport">客户列表</a></li>
                    <li className="active">客户明细</li>
                </ol>
            </_ContentHeader>
            <div className="content">
                <div className="row">
                    <_UserInfoContent location={location} />
                    <_UserEventContent />
                </div>
            </div>
        </div>
    }
}

const _UserDetail = connect(
    state => {
        return {
            searchTime: state.searchTime

        }
    },
    dispatch => {
        return {
            getVisit: (time) => {
                actions.getVisit(dispatch, time);
            },
        }
    }
)(UserDetail);

const _ContentHeader = connect(
    function (state) {
        return {
            socialAccount: state.socialAccount
        }
    }
)(ContentHeader)

class UserEventContent extends Component {
    render() {
        let { userInfo, /*moreEventMessageType, changeMoreEventMessageType, cur_next_id*/ } = this.props;
        return <div className="col-md-8">
            <div className="box box-solid">
                <DetailHeader
                    headImage={userInfo.headImage}
                    name={userInfo.customerName}
                    details={[
                        { title: '创建时间', detail: userInfo.createTimestamp }
                    ]}
                />
            </div>
            <_DetailEvents />
        </div>

    }
}

const _UserEventContent = connect(
    function (state) {
        return {
            userInfo: state.userDetail.userInfo,
            /*moreEventMessageType: state.userDetail.moreEventMessageType,
            cur_next_id: state.userDetail.cur_next_id*/
        }
    },
    function (dispatch) {
        return {
            /*changeMoreEventMessageType: (params) => {
                actions.changeMoreEventMessageType(dispatch, params);
            }*/
        }
    }
)(UserEventContent);

const _DetailEvents = connect(
    (state) => {
        return {
            eventList: state.userDetail.eventLists,
            page: state.userDetail.page,
            size: state.userDetail.size,
            faceId: state.userDetail.userInfo.faceId,
            headImage: state.userDetail.userInfo.headImage,
            eventTypeMap: eventTypeMap,
            isPending: state.userDetail.moreEventMessageType == 1,
            isFinish: state.userDetail.moreEventMessageType == 2,
            moreEventMessageType: state.userDetail.moreEventMessageType
        }
    },
    (dispatch) => {
        return {
            loadMore: (params) => actions.eventListRenderData(dispatch, params)
        }
    }
)(DetailEvents);

/*class EventLists extends Component {
    render() {
        const { eventLists } = this.props;
        let curItem = "";
        let curItem1 = "";
        let curArr = [],
            msgType = 'click,VIEW,subscribe,unsubscribe,SCAN,image,location,voice,video,link,shortvideo,tag,untag';
        eventLists ? eventLists.map(function (item, index) {
            if (curItem != moment(item.event_time).format('YYYY-MM-DD')) {
                curItem = moment(item.event_time).format('YYYY-MM-DD')
                curArr.push(item);
            }
            curArr.push(item)
        }) : ""
        return <ul className="timeline zIndex0">
            {
                curArr ? curArr.map(function (item, index) {
                    if (curItem1 != moment(item.event_time).format('YYYY-MM-DD')) {
                        curItem1 = moment(item.event_time).format('YYYY-MM-DD')
                        return <li className="time-label" key={"eventList" + index}>
                            <span className=" user-detail-time-label" style={{ padding: '5px 10px' }}>{moment(item.event_time).format('YYYY-MM-DD')}</span>
                        </li>
                    }
                    return <li key={item.event_id}>
                        <i className={iconList[item.event_type]}></i>
                        <div className="timeline-item">
                            <div className="timeline-header no-border">
                                <span className="text-bold">{moment(item.event_time).format('HH:mm:ss')}</span>
                                <span >
                                    {eventListType[item.event_type]}
                                    {
                                        item.event_type == 'text' ? item.event_content :
                                            item.event_type == 'SCAN' ? <QrCode url={"https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + item.event_content_display} /> :
                                                item.event_type.indexOf(msgType) ? item.event_content_display : ""
                                    }
                                </span>
                                {item.event_type == "VIEW" ? <a href={item.event_content} target="_blank" className="fa fa-eye pull-right"></a> : ""}
                                {item.event_type == "CLICK" ? <a href={item.event_content} target="_blank" className="fa fa-eye pull-right"></a> : ""}
                            </div>
                        </div>
                    </li>
                }) : ""
            }
        </ul>
    }
}

const _EventLists = connect(
    function (state) {
        return {
            eventLists: state.userDetail.eventLists
        }
    }
)(EventLists)

class QrCode extends Component {
    constructor() {
        super();
        this.state = {
            largeQrCode: false
        }
    }
    mouseOver() {
        this.setState({
            largeQrCode: true
        })
    }
    mouseLeave() {
        this.setState({
            largeQrCode: false
        })
    }
    render() {
        const { url } = this.props;
        const largeQrCode = this.state.largeQrCode,
              mouseOver = this.mouseOver.bind(this),
              mouseLeave = this.mouseLeave.bind(this);
        return <div onMouseLeave={mouseLeave} className="qrCodeContainer">
            <img onMouseOver={mouseOver} className="qrCodeImg" src={url} />
            {
                largeQrCode ? <img className="largeQrCodeImg" src={url} /> : ""
            }
        </div>
    }
}*/

class EventDateSelector extends ReactDropDownFull {
    render() {
        let { eventDateRangeType, selectEventDateRange, startTime, endTime, setStartTime, setEndTime } = this.props;
        const { isOpen } = this.state;
        eventDateRangeType = (typeof eventDateRangeType == 'undefined' ? 2 : eventDateRangeType);

        return <div className="dropdown pull-right zIndex100" ref="parent">
            <a href="javascript:void(0)" className="btn btn-default dropdown-toggle" onClick={() => this.trigger()}>{eventDateRangeList[eventDateRangeType].name}
                <span className="caret"></span>
            </a>
            {isOpen ? <div className="tags-input-list-wrapper" onClick={() => this.close()}>
                <ReactDropDown target={this.refs.parent} selected={eventDateRangeType} data={eventDateRangeList} callback={(eventDateRangeType) => selectEventDateRange(eventDateRangeType)} />
            </div> : null}
            {eventDateRangeType == 3 ? <div>
                <span>开始时间</span>
                <DatePicker selected={startTime} dateFormat="YYYY-MM-DD" locale="zh-cn" onChange={(startTime) => setStartTime(startTime)} />
            </div> : ''}
            {eventDateRangeType == 3 ? <div>
                <span>结束时间</span>
                <DatePicker selected={endTime} dateFormat="YYYY-MM-DD" locale="zh-cn" onChange={(endTime) => setEndTime(endTime)} />
            </div> : ''}
        </div>
    }
}

//为选择器绑定状态
const _EventDateSelector = connect(
    function (state) {
        return {
            eventDateRangeType: state.userDetail.eventDateRangeType,
            startTime: state.userDetail.startTime,
            endTime: state.userDetail.endTime,
        }
    },
    function (dispatch) {
        return {
            setStartTime: (startTime) => {
                dispatch({
                    type: 'select-start-time',
                    val: startTime
                })
            },
            setEndTime: (endTime) => {
                dispatch({
                    type: 'select-end-time',
                    val: endTime
                })
            },
            selectEventDateRange: (eventDateRangeType, params) => {
                actions.selectEventDateRange(dispatch, eventDateRangeType);
            }
        }
    }
)(EventDateSelector);

class UserInfoContent extends Component {
    constructor() {
        super();
        this.state = {
            lifeCycle: 0
        }
    }
    componentDidMount() {
        const { userInfo } = this.props;
        this.setState({
            lifeCycle: lifeCycleList[userInfo[18]]
        })
    }
    handleUpdateMetaDataLifeCycle(val) {
        this.setState({
            lifeCycle: val
        })
        let userId = this.props.userInfo[11]
        let params = {
            lifeCycle: val,
            openId: userId
        };
        this.props.updateMetaDataLifeCycle(params);
    }
    render() {
        const { userInfo,
            location,
            customerOrder,
            order,
            editUserInfo,
            saveUserInfo,
            isLinkOrder,
            linkUserOrder,
            closeLinkOrderPopup,
            confirmLinkUserOrder,
            isPending,
            isFinish,
            loadMore
            } = this.props;
        const handleUpdateMetaDataLifeCycle = this.handleUpdateMetaDataLifeCycle.bind(this),
            lifeCycle = this.state.lifeCycle;
        const properties = [
            { name: '姓名', content: userInfo.customerName || '' },
            { name: '昵称', content: userInfo.nickname || '' },
            { name: '性别', content: userInfo.gender || '' },
            { name: '联系地址', content: userInfo.address || '' },
            { name: '电话号码', content: userInfo.mobile || '' },
            { name: '邮箱', content: userInfo.email || '' },
            // { name: '分组', content: userInfo[7] },
            { name: '创建时间', content: userInfo.createTimestamp || '' },
            // {
            //     type: 'select',
            //     name: '生命周期',
            //     val: lifeCycle,
            //     callback: handleUpdateMetaDataLifeCycle,
            //     list: [
            //         { name: '关注粉丝', value: 1 },
            //         { name: '销售线索', value: 2 },
            //         { name: '高质量线索', value: 3 },
            //         { name: '销售机会', value: 4 },
            //         { name: '意向客户', value: 5 },
            //         { name: '付费客户', value: 6 },
            //         { name: '忠诚客户', value: 7 },
            //         { name: '其他', value: 8 }
            //     ]
            // }
        ];
        return <div className="col-md-4 user-detail-property">
            <BriefUserInfo userInfo={userInfo} />
            <DetailPropertyGroup title="客户信息" properties={properties} userInfo={userInfo} editUserInfo={editUserInfo} saveUserInfo={saveUserInfo} />
            <DealTimeline title="客户订单记录" { ...this.props } />
        </div>
    }
}

const _UserInfoContent = connect(
    function (state) {
        return {
            userInfo: state.userDetail.userInfo,
            customerOrder: state.userDetail.customerOrder,
            order: state.userDetail.order,
            isLinkOrder: state.isLinkOrder,
            isPending: state.userDetail.customerOrder.moreOrderData == 1,
            isFinish: state.userDetail.customerOrder.moreOrderData == 2
        }
    },
    function (dispatch) {
        return {
            updateMetaDataLifeCycle: (params) => {
                actions.updateMetaDataLifeCycle(dispatch, params);
            },
            editUserInfo: (e) => {
                var name = e.target.name;
                var value = e.target.value;
                var param = { name, value };
                dispatch({
                    type: 'edit-user-info',
                    val: param
                });
            },
            saveUserInfo: (params) => {
                actions.saveUserInfo(dispatch, params);
            },
            linkUserOrder: () => {
                dispatch({
                    type: 'link-user-order'
                })
            },
            closeLinkOrderPopup: () => {
                dispatch({
                    type: 'close-link-order'
                });
            },
            confirmLinkUserOrder: (order, userInfo) => {
                var data = order.length > order.skip ? order.data.slice(order.skip - limit, order.skip) : order.data;
                data = data[order.checked[0]];
                actions.confirmLinkUserOrder(dispatch, { dealId: data.dealId, customerId: userInfo.customerId });
            },
            loadMore: (params) => {
                actions.setUserOrder(dispatch, params);
            }
        }
    }
)(UserInfoContent)


class BriefUserInfo extends Component {
    constructor(props) {
        super(props);
        this.state = {
            previewVisible: false,
            previewImage: '',

        }
    }
    handleCancel() {
        this.setState({
            previewVisible: false
        })
    }
    handlePreview(file) {
        this.setState({
            previewImage: file,
            previewVisible: true,
        });
    }
    render() {

        const { userInfo } = this.props;
        const { previewVisible, previewImage } = this.state;

        return (
            <div className="box box-solid briefInfo">
                <div className="box-body">
                    <div className="userImg">
                        {/* <img src={`http://120.27.20.74:8080/face/pic/${userInfo.headImage}.jpg`} alt={userInfo.customerName} />
                        <div className="cover"><a href="javascript:void(0)"> 更改头像</a></div> */}
                        <div onClick={this.handlePreview.bind(this, `http://120.27.20.74:8080/face/pic/${userInfo.headImage}.jpg`)} style={{ width: 100, height: 100, cursor: 'pointer', borderRadius: 4, backgroundImage: `url(http://120.27.20.74:8080/face/pic/${userInfo.headImage}.jpg)`, backgroundSize: 'cover', backgroundPosition: 'center' }}></div>
                    </div>
                    <div className="userInfo">
                        <h3>{userInfo.customerName}</h3>
                        <h5>{userInfo.address}</h5>
                    </div>

                </div>
                <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel.bind(this)}>
                    <img alt="example" style={{ width: '100%' }} src={previewImage} />
                </Modal>
            </div>
        );
    }
}

class GetEventListData extends Component {
    // componentDidMount() {
    //     const { page, size, customerId } = this.props;
    //     this.props.getData({
    //         page: page,
    //         size: size,
    //         customerId
    //     })
    // }
    componentDidUpdate() {
        const { page, size, faceId } = this.props;
        this.props.getData({ page, size, faceId })
    }
    render() {
        return <nodiv></nodiv>
    }
}

const _GetEventListData = connect(
    function (state) {
        return {
            page: state.userDetail.page,
            size: state.userDetail.size,
            faceId: state.userDetail.userInfo.faceId
        }
    },
    function (dispatch) {
        return {
            getData: (params) => {
                actions.eventListRenderData(dispatch, params);
                actions.eventListRequest(dispatch, params)
            }
        }
    }
)(GetEventListData)

class InitialEventListState extends Component {
    componentDidMount() {
        this.commonMethod();

    }
    componentDidUpdate() {
        this.commonMethod();
    }
    commonMethod() {
        const { openId, initialEventListState, setUserOrder, data, setPlatId, platId, visits, currentVisit, location } = this.props;
        let chosenData = data.find(item => { return item.customerId == location.query.userID })
        if (openId != location.query.userID) {
            initialEventListState(chosenData);
            setPlatId(platId);
            setUserOrder({ page: 1, size: 10, customerId: chosenData.customerId });
        }
    }

    redirectUserCenterDetail(data) {
        this.props.closeCenterPopup();
        this.props.setCurrentVisit(data);
        location.href = `#/detail?userID=${data.faceId}`;
    }
    redirectUserBottomDetail(data) {
        this.props.setCurrentVisit(data);
        location.href = `#/detail?userID=${data.faceId}`;
    }

    render() {

        const { visits, visitPage, isHideCenterPopup, isHideBottomPopup, closeCenterPopup, closeBottomPopup, setVisitPage } = this.props;
        const redirectUserCenterDetail = this.redirectUserCenterDetail.bind(this);
        const redirectUserBottomDetail = this.redirectUserBottomDetail.bind(this);

        var start = (visitPage - 1) * 12, end = visitPage * 12 > visits.length ? visits.length : visitPage * 12;
        var arr = visits.slice(start, end);
        var host = window.location.host;
        return <div>
            {
                visits && visits.length > 0 && !isHideCenterPopup || isHideBottomPopup && visits.length > 0 ?
                    <div className="center_layer">
                        <Modal title="来电顾客" footer={null} visible={true} onCancel={closeCenterPopup} footer={[
                            <Button key="back" size="large" onClick={closeCenterPopup}>关闭</Button>,
                            <Button key="submit" type="primary" size="large" onClick={() => { redirectUserCenterDetail(visits[0]) }}>
                                接待顾客
                            </Button>
                        ]} >
                            <img style={{ width: '150px', height: '150px', cursor: 'pointer' }} src={visits.length > 0 ? `http://120.27.20.74:8080/face/pic/${visits[0].headImage}.jpg` : ''} />
                            <p>{visits.length > 0 ? visits[0].nickname : ''}</p>
                        </Modal>
                    </div>
                    :
                    ''
            }
            {
                visits.length > 1 && !isHideBottomPopup ?
                    <div className="bottom_layer">
                        <div className="modal-header">
                            <button type="button" className="close" onClick={closeBottomPopup}><span>&times;</span></button>
                            <h4 className="modal-title">访店顾客</h4>
                        </div>
                        <div className="wait-customer">
                            {
                                visitPage == 1 ?
                                    ''
                                    :
                                    <span className="fa fa-angle-left fa-lg" onClick={() => setVisitPage(visitPage - 1)}></span>
                            }
                            {
                                arr.map((v, index) => {
                                    return <img onClick={() => redirectUserBottomDetail(v)} src={visits.length > 0 ? `http://120.27.20.74:8080/face/pic/${v.headImage}.jpg` : ''} key={index} style={{ cursor: 'pointer' }} />
                                })
                            }
                            {
                                visitPage * 12 >= visits.length ?
                                    ''
                                    :
                                    <span className="fa fa-angle-right fa-lg" onClick={() => setVisitPage(visitPage + 1)}></span>

                            }
                        </div>
                    </div>
                    :
                    ''
            }
        </div>
    }
}

const _InitialEventListState = connect(
    function (state) {
        return {
            data: state.socialList.data,
            platId: state.socialAccount.openID,
            openId: state.userDetail.openId,
            visits: state.visits,
            visitPage: state.visitPage,
            isHideCenterPopup: state.isHideCenterPopup,
            isHideBottomPopup: state.isHideBottomPopup,
            currentVisit: state.currentVisit
        }
    },
    function (dispatch) {
        return {
            initialEventListState: (params) => {
                actions.initialState(dispatch, params);
            },
            setUserOrder: (params) => {
                actions.setUserOrder(dispatch, params);
            },
            setPlatId: (params) => {
                dispatch({
                    type: 'set-plat-id',
                    val: params
                })
            },
            closeCenterPopup: () => {
                dispatch({
                    type: 'hide-center-popup'
                });
            },
            closeBottomPopup: () => {
                dispatch({
                    type: 'hide-bottom-popup'
                });
            },
            setVisitPage: (params) => {
                dispatch({
                    type: 'set-visit-page',
                    val: params
                });
            },
            setCurrentVisit: (data) => {
                dispatch({
                    type: 'set-visit-data',
                    val: data
                });
            }
        }
    }
)(InitialEventListState)

//标签展示组件
class Tags extends Component {
    render() {
        const { tags, location, userId, setUserId, tagList } = this.props;
        const pathName = location ? location.pathname : '/',
            previewModal = location.query.previewModal,
            previewTagModal = location.query.previewTagModal;

        let message = "确定要删除当前标签吗？";
        return <div>
            <span>
                {tagList ? tagList.map(function (ele, index) {
                    return <_LabelCard key={index} data={ele} userId={userId} location={location} />
                }) : ""}
                <div onClick={() => { setUserId(pathName, userId) }} className="badge bg-light-blue addNewTag"><i className="fa fa-plus"></i></div>
            </span>
            <div className="text-left">
                {previewModal ? <_AddTagsModal>
                    <_Preview />
                </_AddTagsModal> : null}
                {previewTagModal ? <_DeleteTagModal>
                    <span>
                        {message}
                    </span>
                </_DeleteTagModal> : null}
            </div>
        </div>
    }
}

const _Tags = connect(
    function (state) {
        return {
            tagList: state.userDetail.data
        }
    },
    function (dispatch) {
        return {
            setUserId: (pathName, userId) => {
                location.href = '#' + pathName + '?previewModal=' + userId;
                actions.setUserId(dispatch, userId);
            }
        }
    }
)(Tags)

//单个标签
class LabelCard extends Component {
    handleDeleteTag(pathName, userId) {
        location.href = '#' + pathName + '?previewTagModal=' + userId;
        let tagId = this.props.data.id;
        this.props.setTagId(tagId);
        this.props.setUserId(userId);
    }
    render() {
        const { data, location, userId } = this.props;
        const pathName = location ? location.pathname : '/';

        const handleDeleteTag = this.handleDeleteTag.bind(this);
        return <div className="badge bg-light-blue addNewTag" id={data.id}>
            <span>
                {data.name}
                <i onClick={() => { handleDeleteTag(pathName, userId) }} className="fa fa-remove"></i>
            </span>
        </div>
    }
}

const _LabelCard = connect(
    function (state) {
        return {
            platId: state.socialAccount.openID
        }
    },
    function (dispatch) {
        return {
            setTagId: (params) => {
                dispatch({
                    type: 'set-tag-id',
                    val: params
                })
            },
            setUserId: (params) => {
                dispatch({
                    type: 'set-user-id',
                    val: params
                })
            }
        }
    }
)(LabelCard)

//delete标签
const _DeleteTagModal = connect(
    function (state) {
        return {
            title: "删除标签",
            submitText: "确定",
            data: {
                platId: state.socialAccount.openID,
                userId: state.sendPost.userId,
                tagId: state.sendPost.tagId
            },
            message: state.sendPost.previewMessage,
            isPending: state.sendPost.isPreviewPending
        }
    },
    function (dispatch) {
        return {
            onClose: () => {
                actions.resetPreviewMessage(dispatch)
            },
            onSubmit: (params) => {
                actions.submitAddTagRequest(dispatch);
                actions.deleteTag(dispatch, params)
            }
        }
    }
)(Modal)

//添加标签
const _AddTagsModal = connect(
    function (state) {
        return {
            title: "打标签",
            submitText: "确定",
            data: {
                platId: state.socialAccount.openID,
                tagName: state.sendPost.tagName || '',
                userId: state.sendPost.userId
            },
            message: state.sendPost.previewMessage,
            isPending: state.sendPost.isPreviewPending
        }
    },
    function (dispatch) {
        return {
            onClose: () => {
                actions.resetPreviewMessage(dispatch)
            },
            onSubmit: (params) => {
                actions.submitAddTagRequest(dispatch);
                actions.submitAddTag(dispatch, params)
            }
        }
    }
)(Modal);

class Preview extends Component {
    render() {
        const { tagName, inputTagName, previewError } = this.props;

        return <div className="form-horizontal">
            <div className="form-group" style={{ marginTop: 15, paddingRight: 15 }}>
                <label>
                    <div className="col-sm-2 control-label">标签名</div>
                    <div className="col-sm-10">
                        <input type="text" className="form-control" placeholder="请输入" value={tagName} onChange={inputTagName} />
                        {previewError ? <span className="help-block text-red" style={{ marginBottom: 0 }}>{previewError}</span> : null}
                    </div>
                </label>
            </div>
        </div>
    }
}

const _Preview = connect(
    function (state) {
        return {
            tagName: state.sendPost.tagName || '',
            previewError: state.sendPost.previewError
        }
    },
    function (dispatch) {
        return {
            inputTagName: (e) => dispatch({
                type: 'input-tag-name',
                val: trim(e.target.value)
            })
        }
    }
)(Preview);

export default _UserDetail